/*
 * @Description:
 * @Version: 1.0
 * @Autor: gaoluo
 * @Date: 2021-09-27 09:50:25
 * @LastEditors: gaoluo
 * @LastEditTime: 2021-12-04 11:46:42
 * @FilePath: /nhw/src/utils/token.js
 */

import axios from 'axios';
import { Toast } from 'vant';
import store from '@/store.js';
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? process.env.VUE_APP_SERVERBASE : '';


/**
 * 获取token
 * @param {String} password
 * @param {String} username 
 * @returns 
 */
export async function toLogin({ username = '', password = '' }) {
  try {
    // password = encode(password);
    const res = await axios.get("/nhw/api/mine/login.ajax", {
      params: {
        username,
        password
      },
      timeout: 8000
    });
    return res.data
  } catch (error) {
    console.log(error);
    Toast.fail('网络错误！')
    return Promise.reject(error)
  }
}

/**
 * 通过uakey获取access_token
 * @param {String} uakey 
 */
export async function getTokenByUakey(uakey = '') {
  const tokenObj = getToken();

  if (isValid(tokenObj)) { //没过期
    console.log('没过期')
    return tokenObj.access_token;
  }
  else { //token过期或者失效
    console.log('token过期或者失效')
    return await axios.get("/nhw/api/getToken", {
      params: {
        uakey
      }
    })
  }
}


/**
 * 设置本地token
 * @param {Object} token 
 * @param {String} uakey 
 */
export function setToken(token, uakey) {
  store.state.token = token;
  window.localStorage.setItem("uakey", uakey)
  window.localStorage.setItem('access_token', token.access_token);
  window.localStorage.setItem('expires_in', token.expires_in);
  window.localStorage.setItem('token_time', token.token_time);
}

/**
 * 获取本地token
 * @returns {Object}
 */
export function getToken() {
  return {
    access_token: window.localStorage.getItem('access_token'),
    expires_in: window.localStorage.getItem('expires_in'),
    token_time: window.localStorage.getItem('token_time')
  }
}

/**
 * access_token:null, //access_token值
 * token_time:0, //token 获取时间
 * expires_in:0, //过期时间（0表示不过期）
 * 是否过期或没有 true 有效 ， false 失效
 * @param {Object} token 
 * @returns {Boolean}
 */
export function isValid(token) {
  const currentTime = Date.now();
  const accessToken = token.access_token;
  const tokenTime = token.token_time;
  const expiresIn = token.expires_in;
  return accessToken ? expiresIn == 0 || currentTime - tokenTime < expiresIn * 3600000 : false
}


//字符串转base64
function encode(str) {
  var encode = encodeURI(str);
  var base64 = window.btoa(encode);
  return base64;
}